//
//  WmcCloudClassifyAlbumVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/30.
//

import UIKit
import MJRefresh

// MARK: - WmcCloudClassifyAlbumVC + WmcVMProtocol

extension WmcCloudClassifyAlbumVC: WmcVMProtocol {
    typealias VMType = WmcCloudClassifyAlbumVM
}

// MARK: - [WmcCloudClassifyAlbumVC]

class WmcCloudClassifyAlbumVC: WmcBaseVC {
    // Lifecycle

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        refresh()
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "分类相册"

        if let classifyAlbumDelegate = YPWmcManager.shared.uiDelegate.personCloudAlbumClassifyAlbumDelegate {
            if classifyAlbumDelegate.navigationShowFeedback(.current) {
                makeFeedbackUI()
            }
        } else {
            makeFeedbackUI()
        }

        func makeFeedbackUI() {
            navView.addSubview(contactBtn)
            contactBtn.snp.makeConstraints { make in
                make.centerY.equalTo(navView.backImageView)
                make.right.equalTo(-Wmc_standardEdge.right)
            }
        }

        addSubview(line)
        addSubview(collectionView)
        addSubview(badNetworkView)

        collectionView.addSubview(emptyView)

        line.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(navView.snp.bottom)
            make.height.equalTo(0.5)
        }

        collectionView.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        emptyView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }

        badNetworkView.snp.makeConstraints { make in
            make.edges.equalTo(collectionView)
        }
    }

    override func bindViewAction() {
        contactBtn.yp.addEvent { _ in
            // 调用优化之后的h5页面
            let vm = WmcHtml5VM()
            vm.parameters = nil
            vm.questionType = .None
            vm.path = WmcHtml5VM.Html5Path.feedback
            WmcNavigatorManager.push(.html5Page, parms: vm)
        }

        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.refresh()
        })

        badNetworkView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.refresh()
        }

        NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumDataDidChange(notification:)), name: NSNotification.Name(rawValue: "com.watermark.cloudAlbumDataDidChange"), object: nil)
    }

    @objc
    func photoAlbumDataDidChange(notification: Notification) {
        self.refresh()
    }

    // Private

    private lazy var contactBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "联系我们", image: "cloud_contact".wmc_image)
        btn.setTintColor(.wmc_mainTheme)
        btn.font = 16.wmc_font
        btn.imgSize = 20.wmc_autoHor
        return btn
    }()

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (self.view.bounds.width - 48) / 2.0
        let height = width + 50
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 16
        layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        layout.sectionHeadersPinToVisibleBounds = true

        let collectView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectView.backgroundColor = .wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = true
        collectView.register(WmcCloudClassifyAlbumCell.self, forCellWithReuseIdentifier: "WmcCloudClassifyAlbumCell")
        return collectView
    }()

    private lazy var badNetworkView: WmcBadNetworkEmptyView = {
        let view = WmcBadNetworkEmptyView()
        view.isHidden = true
        return view
    }()

    private lazy var line: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH15_E6E6E6.withAlphaComponent(0.5)
        return view
    }()

    private lazy var emptyView: WmcCloudAllPhotoEmptyView = {
        let view = WmcCloudAllPhotoEmptyView()
        view.isHidden = true
        return view
    }()

    private func refresh() {
        WmcHudManager.loading()
        viewModel.fetchList { [weak self] list in
            WmcHudManager.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            weakSelf.collectionView.mj_header?.endRefreshing()

            weakSelf.emptyView.isHidden = !list.isEmpty
            weakSelf.showRequestFailure(isShow: false)
        } failure: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
            weakSelf.showRequestFailure(isShow: true)
        }
    }

    private func showRequestFailure(isShow: Bool) {
        if viewModel.dataSource.isEmpty {
            collectionView.isHidden = isShow
            badNetworkView.isHidden = !isShow
        } else {
            badNetworkView.isHidden = true
            collectionView.isHidden = false
        }
    }
}

// MARK: UICollectionViewDelegate, UICollectionViewDataSource

extension WmcCloudClassifyAlbumVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcCloudClassifyAlbumCell", for: indexPath) as! WmcCloudClassifyAlbumCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.row) {
            cell.bindModel(model)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let model = viewModel.dataSource.yp.object(at: indexPath.row) else { return }

        if model.typeEnum() == .allPhoto {
            let vm = WmcClassifyAlbumDetailVM()
            vm.title = model.title
            vm.type = .allPhoto
            vm.dataNeedUpdate = { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.refresh()
            }
            WmcNavigatorManager.push(.allPhoto, parms: vm)?.hidesBottomBarWhenPushed = true
        } else if model.typeEnum() == .watermarkPhoto {
            let vm = WmcClassifyAlbumSecondLevelVM()
            vm.title = model.title
            vm.dataNeedUpdate = { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.refresh()
            }
            WmcNavigatorManager.push(.classifyAlbumSecondLevel, parms: vm)?.hidesBottomBarWhenPushed = true
        }
    }
}
